<template>
  <div class="max">
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>






    <div class="aa">
      <el-form :inline="true" :model="model" class="demo-form-inline">
        <el-form-item label="模型名称">
          <el-input v-model="model.name" placeholder="模型名称"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-input v-model="model.type" placeholder="类型"></el-input>
        </el-form-item>
        <el-form-item label="总分">
          <el-input v-model="model.totalScore" placeholder="总分"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button type="primary" @click="add()">新增</el-button>
          <el-button type="success" @click="beginEdit">初始化配置</el-button>
          <el-button type="success" @click="handleExport">模型下载</el-button>
          <el-button type="success" @click="handleImport">模型上传</el-button>


        </el-form-item>
      </el-form>
    </div>
    <el-dialog
      :visible.sync="addialog"
      width="30%"
      :before-close="cancel"
    >

            <span slot="footer" class="dialog-footer">
                <el-form ref="form" :model="form" label-width="80px">
                <el-form-item label="模型名称" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="类型" prop="type">
                    <el-input v-model="form.type"></el-input>
                </el-form-item>
                <el-form-item label="总分" prop="totalScore">
                    <el-input v-model="form.totalScore"></el-input>
                </el-form-item>
                <el-form-item label="对象应用" prop="objectApplication">
                    <el-input v-model="form.objectApplication"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input v-model="form.description"></el-input>
                </el-form-item>
                 <el-form-item label="阈值管理" prop="thresholdManagement">
                    <el-input v-model="form.thresholdManagement"></el-input>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="addSave" v-if="addflag">保存新增</el-button>
                    <el-button type="primary" @click="updateSave" v-if="updateflag">保存更新</el-button>
                    <el-button @click="cancel">取消</el-button>
                </el-form-item>
                </el-form>


            </span>
    </el-dialog>
    <el-table
      border
      :data="tableData"
      style="width: 100%"
      :row-class-name="tableRowClassName">
      <el-table-column
        prop="name"
        label="模型名称"
        width="200">

      </el-table-column>

      <el-table-column
        prop="type"
        label="类型"
        width="200">
      </el-table-column>

      <el-table-column
        prop="totalScore"
        label="总分"
        width="50">
      </el-table-column>

      <el-table-column
        prop="objectApplication"
        label="对象应用"
        width="80">
      </el-table-column>
      <el-table-column
        prop="description"
        label="描述"
      >
      </el-table-column>

      <el-table-column
        prop="thresholdManagement"
        label="阈值管理">
      </el-table-column>
      <el-table-column
        prop="state"
        label="是否应用"
        width="80">
      </el-table-column>
      <el-table-column
        label="操作"
      align="center">
        <template slot-scope="scope">
          <el-button type="success"  size="mini" @click="update(scope.row)">修改</el-button>
          <el-button type="danger"  size="mini" @click="deleteh(scope.row)">删除</el-button>
          <el-button type="primary"  size="mini" @click="application(scope.row)">对象应用</el-button>
          <el-button type="info"  size="mini" @click="copy(scope.row)">镜像复制</el-button>
        </template>


      </el-table-column>

    </el-table>


      <pagination
        :total="total"
        :page.sync="model.pageNum"
        :limit.sync="model.pageSize"
        @pagination="getList"
      />

  </div>

</template>

<script>  window._interceptConfig = {
  collection: true, //整体开关
  click: true, //页面点击事件信息采集开关
  page: true, //页面跳转加载事件信息采集开关
  error: true, //异常信息采集开关
  http: true, //通讯信息采集开关
  name: "jyzdhywxxxtsdfx_n_prd.mart-ui-ds", //系统编号，被采集信息的系统名称。前端简称
  url: " http://apm.sd.sgcc.com.cn:19411/api/v2/spansWeb"//数据上报服务地址，根据实际情况输入
};
</script>
<!-- src -->
<script src=" http://25.41.37.249:19411/assets/js/intercept.min.js " async></script>
<script>
  import {queryHealthModel,deleteHealthModel,addHealthModel,queryHealthModelById,updateHealthModel,copyHealthModel} from "@/api/system/expertmodel"
  import { getToken } from "@/utils/auth";
  import cache from '@/plugins/cache'
  export default {
    methods: {
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
      },
      mapInputData(){
        const sm2 = require('sm-crypto').sm2
        const sm3 = require('sm-crypto').sm3
        const cipherMode = 1;// 1 - C1C3C2，0 - C1C2C3，默认为1
        var publicKey = cache.session.get("pub")// process.env.VUE_APP_JM
        //《3》
        var nonce_client = new Date().getTime()   //需要生成仅一此有效的字符串，这里用时间戳代替。

        let time = new Date().getTime()

        // 《4》  得到uid
        var uid = cache.session.get("uid")


        this.upload.headers.nonceclient = nonce_client

        //console.log("time shi  " ,time)
        //console.log("timestamp shi  " + cache.session.get("time"))
        var timestamp = (cache.session.get("time")-0) +(time -0);
        //console.log("总数是",timestamp)
        //< 5 > sign_client=hash(timestamp+nonce_client+uid)

        //var sign_client=hash(timestamp+nonce_client+uid)

        //console.log("看看生成的sign_client",sign_client)
        const hash = sm3(timestamp+","+nonce_client+","+uid);
        //《6》 hash
        //console.log("hash值   ",hash)

        this.upload.headers.hash = hash

        this.upload.headers.time = timestamp
        //加密后的hash值
        //《6》
        //var co = SM3((config.data+cache.session.get("uid")))
        // console.log("当前的configdata",config.data)
        // console.log("当前的url",config.url)

        //测试，用来验证前后端对象  是否相同


        //config.headers['data'] = data
        // (1) 数据完整性
        var wzxtime = timestamp;
        //console.log("wzx time e zhi ",wzxtime)

        const wzxdata = sm3(""+","+uid+","+timestamp);
        //console.log("wzxdata 的值 ",wzxdata)

        this.upload.headers.wzxdata = wzxdata


        this.upload.headers.wzxtime = wzxtime
        this.upload.headers

      },
      downloadFile(fileName) {
        let a = document.createElement("a");
        a.href = "/moxing.pdf";
        a.download = 'moxing.pdf';
        a.click();
      },
      cancel(){
        this.$refs['form'].resetFields()
        this.addialog=false

      },

      add(){
        this.addialog=true
        this.addflag=true
        this.updateflag=false
      },
      addSave(){
        addHealthModel(this.form).then(res=>{
          this.$alert(res.msg, '提示', {
          });
          this.addialog=false
          this.$refs['form'].resetFields()
          this.getList()
        })


      },
      update(row){
        queryHealthModelById(row).then(res=>{
          this.form=res.data
        })
        this.updateflag=true
        this.addflag=false
        this.addialog=true
      },
      updateSave(){
        updateHealthModel(this.form).then(res=>{
          this.$alert(res.msg, '提示', {
          });
          this.addialog=false
          this.form.id=''
          this.$refs['form'].resetFields()
          this.getList()
        })

      },
      deleteh(row){

        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteHealthModel(row).then(res=>{
            this.$alert(res.msg, '提示', {
            });
            this.getList()
          })



        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });




      },
      onSubmit(){
        // queryHealthModel(this.model).then(res=>{
        //   this.tableData=res.data
        // })
        this.getList();
      },
      application(row){
        this.$confirm('是否应用对象', '对象应用', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          row.state = '已应用'
          updateHealthModel(row).then(res=>{
            //this.form=res.data
            this.getList()
            this.$alert('对象应用成功', '提示', {
              confirmButtonText: '确定',
            });
          })
        });
      },
      copy(row){

        copyHealthModel(row).then(res=>{
          this.$alert('复制成功', '镜像复制', {
            confirmButtonText: '确定',
          });
          this.getList()
        });
      },

      beginEdit(){
        this.$confirm('初始化配置将清空所有数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.tableData.forEach(e=>{
            deleteHealthModel(e).then(res=>{

            });
          })
          this.tableData=[]

        })



      },
      tableRowClassName({row, rowIndex}) {
        if (rowIndex === 1) {
          return 'warning-row';
        } else if (rowIndex === 3) {
          return 'success-row';
        }
        return '';
      },
      getList(){

        queryHealthModel(this.model).then(res=>{
          this.tableData=res.rows
          this.total = res.total;

        })
      },
      handleExport() {
        this.download('healthModelController/export', {
          ...this.queryParams
        }, `${new Date().getTime()}.xlsx`)
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "健康模型导入";
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        this.download('/healthModelController/importTemplate', {
        }, `health_${new Date().getTime()}.xlsx`)
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.mapInputData()
        this.$refs.upload.submit();
      }




    },
    data() {
      return {
        currentPage: 4,
        addflag:false,
        updateflag:false,
        form: {
          id:'',
          name: '',
          type: '',
          totalScore:'',
          description:'',
          objectApplication:'',
          thresholdManagement:''

        },
        tableData: [],
        model: {
          pageNum: 1,
          pageSize: 10,
          name: '',
          type: '',
          totalScore:''
        },
        addialog:false,
        // 总条数
        total: 0,
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/healthModelController/importData"
        },
      }

    },
    created(){
      this.getList()
    }






  }
</script>

<style scoped>

  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }

  .aa{
    margin-top: 30px;
    margin-left: 50px;
  }
  .max{
    overflow: auto;
  }
</style>
